﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SDT.DataService.Contexts;
using SDT.DataService.Repositories;
using SDT.DataService;
using SDT.Libraries.Utilities;

namespace SDT.DataService.Services
{
   public class LinkDownloadService : IService<Spider_LinkDownload>
    {
        #region Field
       
        private IRepository<Spider_LinkDownload> repository;
        #endregion
       
        #region Constructor
        public LinkDownloadService()
            : this(new Repository<Spider_LinkDownload>())
        {
        }

        public LinkDownloadService(IRepository<Spider_LinkDownload> repository)
        {
            this.repository = repository;
           
        }
        #endregion

        #region Store Procedure
     
        public int UpdateLinkDownload(int id, string pFile)
        {
             LinkDownloadContext contextObj = new LinkDownloadContext();
             SystemSpiderDataContext spiderDataContext = new SystemSpiderDataContext(); // Vietlv(28/09/2011)
             FTC_BDSDataContext eDataContext = new FTC_BDSDataContext();
             var currentLinkDownload = spiderDataContext.Spider_LinkDownloads.Where(e => e.DowloadID == id).SingleOrDefault(); // Vietlv(28/09/2011)
             var currentArticles = eDataContext.Ads.Where(e => e.PageID == currentLinkDownload.PageID).SingleOrDefault(); // Vietlv(28/09/2011)
             currentArticles.Image = pFile; 
             currentArticles.Status = 2; 
             eDataContext.SubmitChanges(); 
            try
            {
                return contextObj.UpdateLinkDownloadAll(id, pFile);
            }
            catch (Exception ex)
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "UpdateLinkDownload", ex.Message));
                return 0;
            }
            finally { contextObj.Dispose(); }

        }
        // Created by: Vietlv
        // Created date: 05/07/0211
        // Description: Update path file image to other database

        public int UpdateLinkDownloadToOtherDB(int id, string pFile)
        {
            FTC_BDSDataContext eDataContext = new FTC_BDSDataContext();
            SystemSpiderDataContext spiderDataContext = new SystemSpiderDataContext();
            try
            {
                var currentLinkDownload = spiderDataContext.Spider_LinkDownloads.Where(e => e.DowloadID == id).SingleOrDefault();
                var currentArticles = eDataContext.Ads.Where(e => e.PageID == currentLinkDownload.PageID).SingleOrDefault();
                currentArticles.Image = pFile;
                currentArticles.Status = 2;
                eDataContext.SubmitChanges();

                currentLinkDownload.PathSaveFile = pFile;
                currentLinkDownload.Status = 2;
                spiderDataContext.SubmitChanges();
                return 1;
            }
            catch (Exception exp)
            {
                new LogException().Write(string.Format(" Module {0} -- Msg {1}", "UpdateLinkDownload", exp.Message));
                return 0;
            }
            finally { eDataContext.Dispose(); }
        }
       /// <summary>
       /// Created by Vietlv 
       /// Created date: 21/09/2011
       /// Desciption: Kiem tra xem bai viet da co anh dai dien hay chua? neu chua co link anh thi them moi. Con neu co roi thi thoi.
       /// </summary>
       /// <returns></returns>
        public int Insert_LinkDownload(int pageid, string url, byte status,byte typeint, bool isImage, int cateid, int siteid, int totalfile)
        {
            SystemSpiderDataContext eDataContext = new SystemSpiderDataContext();
            var CurrentLinkDownload = eDataContext.Spider_LinkDownloads
                                        .Where(e => pageid > 0 ? e.PageID == pageid : false)
                                        .FirstOrDefault();
            if (CurrentLinkDownload == null || (CurrentLinkDownload != null && CurrentLinkDownload.LinkURL.Trim().Length < 1)) // Trường hợp chưa có linkdownload trong bảng linkdownload
            {
                LinkDownloadContext contextObj = new LinkDownloadContext();
                try
                {
                    return contextObj.sp_WC_LinkDownload_Insert(pageid, url, status, typeint, isImage, cateid, siteid, totalfile);
                }
                catch (Exception ex)
                {
                    new LogException().Write(string.Format("  Module {0} --Msg {1} ", "Insert_LinkDownload", ex.Message));
                    return 0;
                }
                finally { contextObj.Dispose(); }
            }
            else
            {
                return 0;
            }
        }
       /* Ham Goc VietLv dao Ngay 21/09/2011 
        public int Insert_LinkDownload(int pageid, string url, byte status, byte typeint, bool isImage, int cateid, int siteid, int totalfile)
        {
            LinkDownloadContext contextObj = new LinkDownloadContext();
            try
            {
                return contextObj.sp_WC_LinkDownload_Insert(pageid, url, status, typeint, isImage, cateid, siteid, totalfile);
            }
            catch (Exception ex)
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "Insert_LinkDownload", ex.Message));
                return 0;
            }
            finally { contextObj.Dispose(); }
        }
         */
        //public void Insert_LinkDownload(List<Spider_LinkDownload> listLinkDownload)
        //{
        //    //edit by trungdt
        //    //date 18/12/2010
        //    //su dung linq de batch insert trong 1 lần kết nối

        //    BDS_SpiderDataContext contextObj = new BDS_SpiderDataContext();
        //    try
        //    {
        //        contextObj.Spider_LinkDownloads.InsertAllOnSubmit(listLinkDownload);
        //        if (listLinkDownload[0].IsImageDesc.Equals(true))
        //        {
        //             Article objUpdatedNews = (from sitenew in contextObj.Articles where sitenew.PageID.Equals((int)listLinkDownload[0].PageID) select sitenew).First();
        //            if (objUpdatedNews != null)
        //                objUpdatedNews.ImgPath = listLinkDownload[0].LinkURL;
        //        }
        //        contextObj.SubmitChanges();
        //    }
        //    catch (Exception ex)
        //    {
        //        new LogException().Write(string.Format("  Module {0} --Msg {1} ", "Insert_LinkDownload", ex.Message));
        //    }
        //    finally { contextObj.Dispose(); }

        //}

        public int ChangeStatus(int id, byte status)
        {
            LinkDownloadContext contextObj = new LinkDownloadContext();
            try 
            {
                return contextObj.sp_MD_LinkDownload_ChangeStatus(id, status);            
            }
            catch(Exception ex) 
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "Class LinkService. Method : ChangeStatus", ex.Message));
                return 0;
            }
            finally { contextObj.Dispose(); }

        }
        #endregion

        #region Method
        //public IList<Spider_LinkDownload> GetBatchSizeList(int BatchCount, byte statusSucc, int nTry)
        //{
        //    IList<Spider_LinkDownload> list = this.GetAll().Where(itm => itm.Status != statusSucc && itm.TotalTryAgain < nTry).
        //        OrderByDescending(itm => itm.IsImageDesc).
        //        OrderBy(itm => itm.DowloadID).
        //        Take(BatchCount).ToList();
        //    return list;

        //}

        //public IList<Spider_LinkDownload> GetBatchSizeList(int BatchCount, byte statusSucc,int maxID, int nTry)
        //{
        //    IList<Spider_LinkDownload> list = this.GetAll().Where(itm => itm.Status != statusSucc && itm.TotalTryAgain < nTry && itm.DowloadID > maxID).
        //        OrderByDescending(itm => itm.IsImageDesc).
        //        OrderBy(itm => itm.DowloadID).
        //        Take(BatchCount).ToList();
        //    return list;

        //}
        public IList<Spider_LinkDownload> GetBatchSizeList()
        {
            LinkDownloadContext contextObj = new LinkDownloadContext();
            try
            {
                return contextObj.sp_WC_LinkDownLoad_SelectList().Select(lk => new Spider_LinkDownload() {
                    CategoryID = lk.CategoryID,
                    CreatedDate = lk.CreatedDate,
                    DowloadID = lk.DowloadID,
                    IsImageDesc = lk.IsImageDesc,
                    LastDate = lk.LastDate,
                    LinkURL = lk.LinkURL,
                    PageID = lk.PageID,
                    PathSaveFile = lk.PathSaveFile,
                    SiteID = lk.SiteID,
                    Status = lk.Status,
                    TotalFile = lk.TotalFile,
                    TotalFileReceive = lk.TotalFileReceive,
                    TotalTryAgain = lk.TotalTryAgain,
                    TypeFile = lk.TypeFile
                }).ToList();
            }
            catch (Exception ex)
            {
                new LogException().Write(string.Format("  Module {0} --Msg {1} ", "GetBatchSizeList", ex.Message));
                return null;
            }
            finally { contextObj.Dispose(); }

        }
        //public IList<Spider_LinkDownload> GetList(int BatchCount, byte statusSucc, int nTry, ref int maxID)
        //{
        //    IList<Spider_LinkDownload> list = null;
        //    if (maxID == 0)
        //    { 
        //        list = this.GetBatchSizeList(BatchCount, statusSucc, nTry);
        //        maxID = Convert.ToInt32(list.Max(itm => itm.DowloadID).ToString());
        //    }
        //    else
        //    {
        //        list = GetBatchSizeList(BatchCount, statusSucc, maxID, nTry);
        //        if (list.Count == 0 || list ==null) maxID = 0;
        //        else
        //        {
        //            int x = Convert.ToInt32(list.Max(itm => itm.DowloadID).ToString());
        //            if (maxID == x) maxID = 0;
        //            else if (maxID < x) maxID = x;
        //        }
        //    }
        //    return list;
        //}

        #endregion

        #region IService<Spider_LinkDownload> Members

        public IQueryable<Spider_LinkDownload> GetAll()
        {
            return repository.GetAll();
        }

        public bool Update(Spider_LinkDownload entity)
        {
            throw new NotImplementedException();
        }

        public bool Create(Spider_LinkDownload entity)
        {
            throw new NotImplementedException();
        }

        public bool Delete(Spider_LinkDownload entity)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
